package com.optitronics.service.impl;

import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.optitronics.beans.Reseller;
import com.optitronics.service.MailSendingService;
import com.optitronics.service.ResellerService;
import com.optitronics.ui.ResellerForm;
import com.optitronics.util.OptitronicsUtils;

@Service
public class ResellerServiceImpl implements ResellerService {

	@Autowired
	private MailSendingService mailSendingService;

	private Log logger = LogFactory.getLog(this.getClass());

	/**
	 * Saves reseller data
	 * 
	 * @param formObject
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
	public Reseller saveReseller(ResellerForm formObject) {

		logger.info("Saving reseller: email: " + formObject.getEmail() + ", id: " + formObject.getId()
				+ ", tax number: " + formObject.getTaxNumber());

		if (formObject.getTaxNumber() == null) {
			throw new RuntimeException("Data not complete");
		}

		Reseller reseller = new Reseller();
		String originalPassword = formObject.getPassword();

		reseller.setId(formObject.getId());
		reseller.setVersion(formObject.getVersion());
		reseller.setName(formObject.getName());
		reseller.setEmail(formObject.getEmail());
		reseller.setCode(formObject.getCode());
		if (reseller.getId() == null) {
			Md5PasswordEncoder encoder = new Md5PasswordEncoder();
			String md5Password = encoder.encodePassword(formObject.getPassword(), null);
			reseller.setPassword(md5Password);
		} else {
			reseller.setPassword(formObject.getPassword());
		}

		reseller.setStatus(formObject.getStatus());
		reseller.setPhoneNumber(formObject.getPhoneNumber());
		reseller.setTaxNumber(formObject.getTaxNumber());
		reseller.setActivationToken(formObject.getActivationToken());
		reseller.setCity(formObject.getCity());
		reseller.setAddress(formObject.getAddress());

		if (reseller.getId() == null) {

			if (OptitronicsUtils.isUserAdmin()) {
				reseller.setStatus(Reseller.STATUS_ACTIVE);
				mailSendingService.sendResellerInfoMail(reseller, originalPassword);
			} else {
				reseller.setActivationToken(generateActivationToken());
				reseller.setStatus(Reseller.STATUS_WAITING_FOR_ACTIVATION);
				mailSendingService.sendActivationLink(reseller);
			}
		}

		logger.info("Attempting to save reseller: " + reseller.toString());

		reseller.merge();
		return reseller;
	}

	/**
	 * Activates reseler registration
	 * 
	 * @param resellerEmail
	 * @param activationToken
	 * @return true is everything went ok, false otherwise
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
	public boolean activateRegistration(String resellerEmail, String activationToken) {

		logger.info("activating registration, resellerEmail: " + resellerEmail + ", activationToken: "
				+ activationToken);

		Reseller reseller = Reseller.findResellerByEmailAndToken(resellerEmail, activationToken);
		boolean result = true;

		if (reseller != null) {
			reseller.setStatus(Reseller.STATUS_ACTIVE);
			reseller.setActivationToken(null);
			reseller.merge();
		} else {
			logger.warn("Reseller not found for registration data");
			result = false;
		}

		return result;
	}

	/**
	 * Reset password for reseller and send new pass it's on e-mail
	 * 
	 * @param resellerForm
	 */
	public void resetPassword(ResellerForm resellerForm) {

		logger.info("Reseting password for " + resellerForm.getEmail() + ", Tax number: " + resellerForm.getTaxNumber());

		Reseller reseller = Reseller.findResellerByEmailAndTaxNumber(resellerForm.getEmail(),
				resellerForm.getTaxNumber());
		String newPassword = generateActivationToken();
		if (newPassword.length() > 8) {
			newPassword = newPassword.substring(0, 8);
		}

		Md5PasswordEncoder encoder = new Md5PasswordEncoder();
		String md5Password = encoder.encodePassword(newPassword, null);
		reseller.setPassword(md5Password);

		reseller.merge();

		mailSendingService.sendResetPasswordMail(reseller, newPassword);
	}

	private String generateActivationToken() {

		Random r = new Random();
		long r1 = r.nextLong();
		long r2 = r.nextLong();
		String hash1 = Long.toHexString(r1);
		String hash2 = Long.toHexString(r2);

		return hash1 + hash2;

		// long now = System.currentTimeMillis();
		// double random = Math.random() * 1000d;
		// random = random * now;
		// return String.valueOf((long) random);
	}
}
